#!/usr/bin/bash

condition=1
module_name=None
module_list=()
add_opencv=none
add_onnx=none

delete_target ()
{
	for element_idx in ${!module_list[@]}; do
		if [ ${module_list[$element_idx]} == "$1" ]; then
			index=$element_idx
		fi
	done
	unset module_list[$index]
}

write_cmake ()
{
	echo "cmake_minimum_required (VERSION 3.10)" >> CMakeLists.txt
	echo "project ($project_name)" >> CMakeLists.txt
	echo "" >> CMakeLists.txt

	for module in ${module_list[@]}; do
		echo "add_subdirectory ($module)" >> CMakeLists.txt
	done
	echo "" >> CMakeLists.txt

	if [ $add_opencv == "yes" ]; then
		echo "find_package (OpenCV REQUIRED)" >> CMakeLists.txt
	fi

	echo "" >> CMakeLists.txt
	echo "add_executable (main main.cpp)" >> CMakeLists.txt
	echo "" >> CMakeLists.txt
	for module in ${module_list[@]}; do
		echo "target_link_libraries (main $module)" >> CMakeLists.txt
	done
	echo "" >> CMakeLists.txt
	
	if [ $add_opencv == "yes" ]; then
		echo "target_include_directories (main PUBLIC \${OpenCV_INCLUDE_DIRS})" >> CMakeLists.txt
		echo "target_link_libraries (main \${OpenCV_LIBS})" >> CMakeLists.txt
	fi
}

main ()
{
	read -p "Project Name : " project_name
	mkdir $project_name
	cd $project_name

	touch main.cpp
	touch CMakeLists.txt

	while [ $condition != "0" ]; do
		echo ""
		echo "----------------------"
		echo "0. create new module"
		echo "1. delete module"
		echo "2. list modules"
		echo "3. continue"
		echo "4. exit"
		echo ""
		read -p "What do you want to do : " condition
		case $condition in
			("0")
				read -p "The name of the module : " module_name
				mkdir $module_name
				touch $module_name/$module_name\.h
				touch $module_name/$module_name\.cpp
				touch $module_name/CMakeLists.txt
				module_list+=($module_name)
				nvim $module_name/CMakeLists.txt
				echo "#include \"$module_name.h\"" >> $module_name/$module_name\.cpp
				;;

			("1")
				echo ""
				echo ${module_list[*]}
				echo ""
				read -p "Which do you want to delete : " module_name
				rm -r $module_name
				delete_target $module_name
				;;

			("2")
				echo ${module_list[*]}
				;;

			("3")
				read -p "Do you want to add opencv libraries ? (yes/no) " add_opencv
				write_cmake
				for module in ${module_list[@]}; do
					echo "#include \"$module.h\"" >> main.cpp
				done
				break

			("4")
				break
				;;

		esac
		condition=1
	done

	mkdir build
	cd build
	cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ..

}

main
